# -*- encoding=UTF-8 -*-
import json
import os
import time
from datetime import datetime
from time import sleep

import requests
import uiautomator2 as u1
from PIL import Image, ImageStat


class upgrade:

    def __init__(self, devices_name, packageName):
        self.packageName = packageName
        self.d = u1.connect(devices_name)
        self.d.unlock()
        self.d.press("home")
        self.log_path = time.strftime("doorbell_upgrade_%Y_%m_%d_%H_%M_%S", time.localtime()) + '.log'

        if not os.path.exists('./fail_pic/'):
            os.makedirs('./fail_pic/')

    def set_up(self):
        self.d.app_stop(self.packageName)
        sleep(1)
        self.d.app_start(self.packageName)

        gotimes = 0
        while True:
            if self.d(text="Home").exists:
                sleep(3)
                break
            else:
                sleep(3)
                gotimes += 1
            if gotimes == 4:
                break

    def test_down(self):
        self.d.app_stop(self.packageName)

    def write_log(self, file_path, str):
        '''
        报告录入工具
        :param str: 字符串
        :return: None
        '''
        if file_path is not None:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            with open(file_path, "a") as file:
                file.write(t + " " + str + "\n")
                file.close()

    def resize_image(self, file, width, height, type):
        img = Image.open(file)
        out = img.resize((width, height), Image.Resampling.LANCZOS)  # resize image with high-quality
        out.save(file, type)


    def start_upgrade(self, test_num):
        try:
            self.d(text="2").click(timeout=5)

            time.sleep(5)
            self.d(resourceId="com.wyze.gemini:id/gmIvSetting").click(timeout=5)
            self.d(scrollable=True).scroll.toEnd()

            self.d(text="Device Info").click(timeout=5)
            time.sleep(5)
            self.d(text="Firmware Version").click(timeout=5)
            time.sleep(5)
            self.d(text="Update").click(timeout=5)

            start_time = time.time()
            dingTalk = DingMessage()

            is_time_out = True

            while int(time.time()) - int(start_time) < 600:
                if self.d(text='Done').exists():
                    end_time = time.time()
                    total_time = end_time - start_time

                    self.write_log(self.log_path, str="第" + str(test_num) + "次测试，升级成功，耗时#" + str(total_time))
                    dingTalk.test_pass(take_time=int(total_time), test_num=test_num)

                    is_time_out = False
                    break
                if self.d(text='Try Again').exists():
                    sleep(1)
                    error_info = self.d(resourceId="com.wyze.gemini:id/tv_update_info")
                    if error_info.exists():
                        self.write_log(self.log_path, str="第" + str(test_num) + "次测试，升级失败, 错误信息："
                                                          + error_info.info["text"])
                    dingTalk.test_fail(test_num=test_num, info=error_info.info["text"])

                    is_time_out = False
                    break
                sleep(2)

            if is_time_out:
                error_info = self.d(resourceId="com.wyze.gemini:id/tv_update_info")
                if error_info.exists():
                    self.write_log(self.log_path, str="第" + str(test_num) + "次测试，升级失败, 错误信息：" + error_info.text)
                dingTalk.test_time_out(test_num=test_num, info=error_info.info["text"])
            return True

        except Exception as e:
            print(e)
            return False


class DingMessage:
    def __init__(self):
        self.URL = "https://oapi.dingtalk.com/robot/send?" \
                   "access_token=03cd0516496189300b77e672a711669c10e7d172466decd4e6676b1ee4db7051"  # Webhook地址
        self.headers = {'Content-Type': 'application/json'}

    def test_fail(self, test_num, info):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "升级压力测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试异常，设备2升级失败， 错误信息：" + info +
                                                                         "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)

    def test_time_out(self, test_num, info):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "升级压力测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试异常，设备2升级超时， 错误信息：" + info +
                                                                         "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)

    def test_pass(self, test_num, take_time):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "设备2升级压力测试通过提示",
                "text": "#### **<font color=#7CFCOO>第" + str(test_num)
                        + "次测试通过**</font>\n\n""> **升级消耗时长:** <font color=#000000>"
                        + str(take_time) + "秒</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)


if __name__ == '__main__':
    test_time = int(input("请输入测试次数："))
    ug = upgrade(devices_name="0.0.0.0", packageName='com.wyze.gemini')

    count = 1
    while count < test_time + 1:
        ug.set_up()
        if not ug.start_upgrade(test_num=count):
            count -= 1
        else:
            count += 1
